import { message } from 'antd';

export default {
    // 加入购物车
    addToCar(user, goods, props) {
        if (goods.count) {
            goods.count++;
        } else {
            goods.count = 1; // 设置本书购买数量
        }

        let getUsers = window.localStorage.getItem('cars');

        if (getUsers === null) {
            getUsers = {
                "users": [{
                    "user": user,
                    "list": [goods]
                }]
            };
            window.localStorage.setItem('cars', JSON.stringify(getUsers));
        } else {
            getUsers = JSON.parse(getUsers).users;
            let flag = 0;
            getUsers.map(item => {
                if (item.user === user) {
                    flag = 1;
                    item.list.map(i => {
                        if (i.id == goods.id) { // 是同一本书
                            flag = 2;
                            i.count++;
                        }
                    });

                    if (flag == 1) {
                        item.list.push(goods);
                    }
                }
            });

            if (flag == 0) {
                getUsers.push({
                    "user": user,
                    "list": [goods]
                });
            }

            window.localStorage.setItem('cars', JSON.stringify({ users: getUsers }));

            // 提示加入购物车成功
            message.success('加入购物车成功!', 2);
        }
    },
    // 立即购买
    buyNow(user, goods, props) {
        this.addToCar(user, goods, props);
        props.history.push('/shoppingcar');
    }
}